import { getPopupApi } from '@/services/home'
import { useMemberStore } from '@/stores'
import { PageSkip } from '@/utils/tools'
import { onHide, onShow } from '@dcloudio/uni-app'
import { ref } from 'vue'

export default function usePopup() {
  const SkipPopupRef = ref()
  const skipPopupData = ref({
    status: false,
    img: '',
    url: '',
    marketingId: -1,
  })
  /**点击弹窗后的跳转 */
  const receive = () => {
    // console.log('点击按钮')
    const pageList = ['/pages/index/index', '/pages/eat/eat', '/pages/goods/goods', '/pages/my/my']
    const isSkipType = pageList.some((item) => item === skipPopupData.value.url)
    const isHttp = skipPopupData.value.url && skipPopupData.value.url.startsWith('http')
    if (isSkipType && !isHttp) {
      PageSkip(skipPopupData.value.url, 'switchTab')
    } else if (!isHttp) {
      skipPopupData.value.url
        ? PageSkip(skipPopupData.value.url)
        : PageSkip('/pages/eat/eat', 'switchTab')
    } else if (isHttp) {
      PageSkip(`/pagesMy/linkPage/linkPage?_src=${skipPopupData.value.url}`)
    }
    SkipPopupRef.value.close(false)
  }
  /**获取 弹窗 接口*/
  const getPopup = async () => {
    const res = await getPopupApi()
    console.log('获取弹窗接口=====', res.data)
    skipPopupData.value = { ...res.data }
    if (skipPopupData.value.status) {
      setTimeout(() => {
        SkipPopupRef.value.open()
      }, 500)
    }
  }
  const handleClose = () => {
    getPopup()
  }
  onShow(() => {
    const memberStore = useMemberStore()
    if (!memberStore.token) return
    getPopup()
  })
  onHide(() => {
    console.log('onHide')
    SkipPopupRef.value?.close(false) // 页面切换关闭弹窗
  })

  return {
    skipPopupData,
    SkipPopupRef,
    receive,
    getPopup,
    handleClose,
  }
}
